<template>
    <div>
        <div class="content">
            <div class="head">
                <div class="head-input">
                    <div class="input-item">
                        <span class="item-label">备货单号:</span>
                        <el-input
                            v-model="inputForm.stockOrderOrTask"
                            size="small"
                            placeholder="请输入备货单号"
                            clearable
                            class="input"
                        ></el-input>
                    </div>
                    <div class="input-item">
                        <span class="item-label">产品型号:</span>
                        <el-input
                            v-model="inputForm.productModel"
                            size="small"
                            placeholder="请输入产品型号"
                            clearable
                            class="input"
                        ></el-input>
                    </div>
                    <div class="input-item">
                        <span class="item-label">主编码:</span>
                        <el-input
                            v-model="inputForm.mainCode"
                            size="small"
                            placeholder="请输入主编码"
                            clearable
                            class="input"
                        ></el-input>
                    </div>
                </div>
                <div class="head-btn">
                    <el-button
                        type="success"
                        size="small"
                        style="width: 5vw;"
                        @click="addBtn"
                        :disabled="isLoading"
                    >新增</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        style="width: 5vw;"
                        @click="inportExcel_btn"
                        :disabled="isLoading"
                    >导入</el-button>
                    <el-button type="info" size="small" style="width:8vw" @click="templateDownload_btn" title="下载排产表模板" icon="el-icon-document" :loading="templateDownloadBtnLoading" :disabled="isLoading">模板下载</el-button>
                    <el-button
                        size="small"
                        style="width: 5vw;;float:right"
                        @click="reset_btn"
                        :disabled="isLoading"
                    >重置</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        style="width: 5vw;margin-left:1vw;float:right"
                        @click="search_btn"
                        :loading="isLoading"
                        :disabled="isLoading"
                    >查询</el-button>
                </div>
            </div>
            <div class="main">
                <div class="main-table">
                    <el-table style="width: 100%" :data="productOrderList" v-loading="isLoading">
                        <el-table-column prop="erpOrderNumber" label="ERP订单号" width></el-table-column>
                        <el-table-column prop="stockOrderOrTask" label="备货单" width></el-table-column>
                        <el-table-column prop="totalQuantity" label="总数量" width></el-table-column>
                        <el-table-column prop="productModel" label="产品型号" width></el-table-column>
                        <el-table-column prop="mainCode" label="主编码" width></el-table-column>
                        <el-table-column prop="createdDate" label="创建时间" width></el-table-column>
                        <el-table-column fixed="right" label="操作" width="100">
                            <template slot-scope="scope">
                                <el-button type="text" size="small" @click="editRow(scope.row)">编辑</el-button>
                                <el-button type="text" size="small" @click="deleteRow(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="main-pagination">
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @prev-click="previousPage_btn"
                        @next-click="nextPage_btn"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalElements"
                    ></el-pagination>
                </div>
            </div>
        </div>
        <el-dialog :title="dialogFormState === 0 ? '新增' : '编辑'" width="30%" :visible.sync="dialogFormVisible" :show-close="false">
            <el-form size="small" :model="dialogForm" :rules="rules" ref="dialogForm">
                <el-form-item label="ERP订单号" label-width="120px" prop="erpOrderNumber">
                    <el-input style="width: 220px;" v-model="dialogForm.erpOrderNumber"></el-input>
                </el-form-item>
                <el-form-item label="备货单/任务令" label-width="120px" prop="stockOrderOrTask">
                    <el-input style="width: 220px;" v-model="dialogForm.stockOrderOrTask"></el-input>
                </el-form-item>
                <el-form-item label="总数量" label-width="120px">
                    <el-input-number
                        style="width: 220px;"
                        :min="0"
                        v-model="dialogForm.totalQuantity"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="产品型号" label-width="120px" prop="productModel">
                    <el-input style="width: 220px;" v-model="dialogForm.productModel"></el-input>
                </el-form-item>
                <el-form-item label="主编码" label-width="120px" prop="mainCode">
                    <el-input style="width: 220px;" v-model="dialogForm.mainCode"></el-input>
                </el-form-item>
                <el-form-item style="margin:auto 0;text-align: center;">
                    <el-button size="small" @click="dialogFormVisible = false, clearFormData()">取 消</el-button>
                    <el-button
                        size="small"
                        type="primary"
                        @click="dialogFormHandle('dialogForm')"
                        :loading="submitLoading"
                    >确 定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { reqProductOrderList, reqOrderImportExcel, reqUserInfo, saveProductDetail, deleteProductOrderList, reqExportTemplateOfProductionOrder, reqUpdateProductionOrderDetails } from "@/api/project.js";
export default {
    data() {
        return {
            inputForm: {
                stockOrderOrTask: "",
                productModel: "",
                mainCode: ""
            },
            productOrderList: [],  //内存条相关信息
            currentPage: 1,  //当前页数
            totalPage: 1,  //总页数
            totalElements: 0, // 总数量
            pageSize: 10, // 每页数量
            isLoading: false,  //表格数据是否在加载
            dialogFormVisible: false, // 弹窗
            dialogFormState:0,  //0-新增 1-编辑
            dialogForm: { // 弹窗的表单
                erpOrderNumber: '', //erp订单号
                stockOrderOrTask: '',// 备货单号
                totalQuantity: 0,// 总数量
                productModel: '',//产品型号
                mainCode: '',//主编码
                id:""
            },
            rules: { // 规则
                erpOrderNumber: [
                    { required: true, message: '请输入erp订单号', trigger: 'blur' }
                ],
                stockOrderOrTask: [
                    { required: true, message: '请输入备货单号', trigger: 'blur' }
                ],
                productModel: [
                    { required: true, message: '请输入产品型号', trigger: 'blur' }
                ],
                mainCode: [
                    { required: true, message: '请输入主编码', trigger: 'blur' }
                ]
            },
            submitLoading: false,
            templateDownloadBtnLoading:false  //模板下载loading
        }
    },
    mounted() {
        //获取排产订单列表数据
        this.getProductInfoList();
        //判断用户身份是否过期
        this.checkIsValidateUser();
    },
    methods: {
        handleSizeChange: function (val) {
            this.pageSize = val;
            this.getProductInfoList();
        },
        handleCurrentChange: function (val) {
            this.currentPage = val;
            this.getProductInfoList();
        },
        previousPage_btn: function () {
            if (this.currentPage <= 1) return;
            this.currentPage--;
            //重新请求数据
            this.getProductInfoList();
        },
        nextPage_btn: function () {
            if (this.currentPage >= this.totalPage) return;
            this.currentPage++;
            this.getProductInfoList();
        },
        //导入按钮,导入内存条模块excel表
        inportExcel_btn: async function () {
            const _this = this;
            const divBox = document.querySelector(".head-btn");
            let inputDom = document.createElement("input");
            inputDom.style.display = 'none';
            inputDom.type = 'file';
            divBox.appendChild(inputDom);
            inputDom.click();
            inputDom.onchange = async function (event) {
                let file = event.target.files[0];
                let fileType = file.name.substring(file.name.lastIndexOf("."), file.name.length);
                let fileSize = file.size / 1024 / 1024;  //转为MB
                if (fileType !== '.xlsx' && fileType !== '.xls') {
                    _this.$message({ type: 'warning', message: "请选择excel文件!" });
                    return;
                }
                if (fileSize > 10) {
                    _this.$message({ type: 'warning', message: "文件大小不能超过10MB!" });
                    return;
                }
                //准备formData
                const formData = new FormData();
                formData.append('file', file);
                try{
                    let res = await reqOrderImportExcel(formData);
                    if (res.data.code === 200) {
                        _this.$message({ type: "success", message: "文件上传成功!" });
                    } else {
                        _this.$message({ type: "error", message: "文件上传失败，请重试!" });
                    }
                }catch(err){
                    _this.$alert(err.response.data.message, '警告', { confirmButtonText: '确定', callback: action => {}});
                }
            }
            divBox.removeChild(inputDom);  //移除input
        },
        //请求排产订单列表数据
        async getProductInfoList() {
            this.isLoading = true;
            let res = await reqProductOrderList({ page: this.currentPage, size: this.pageSize, sort: 'createdDate,desc', ...this.inputForm });
            if (res.data.code === 200) {
                const { content, totalPages, totalElements } = res.data.data
                this.productOrderList = content;
                this.totalPage = totalPages;
                this.totalElements = totalElements;
                console.log("排产订单列表数据:", res.data);
                this.isLoading = false;
            }
        },
        //根据搜素条件查询内存条列表数据
        async search_btn() {
            if (this.inputForm.stockOrderOrTask !== '' || this.inputForm.productModel !== '' || this.inputForm.mainCode !== '') {
                this.isLoading = true;
                let res = await reqProductOrderList({ page: this.currentPage, size: this.pageSize, sort: 'createdDate,desc', ...this.inputForm });
                if (res.data.code === 200) {
                    this.productOrderList = res.data.data.content;
                    this.totalPage = res.data.data.totalPages;
                    this.totalElements = res.data.data.totalElements;
                    console.log("搜素erp订单列表数据:", res.data);
                    this.isLoading = false;
                }
            } else {
                this.$message({ type: "warning", message: "搜索条件为空!" });
            }
        },
        //重置按钮
        async reset_btn() {
            this.inputForm.stockOrderOrTask = '';
            this.inputForm.productModel = '';
            this.inputForm.mainCode = '';
            this.getProductInfoList();
        },
        //判断当前用户身份是否过期
        async checkIsValidateUser() {
            let res = await reqUserInfo();
            let isExpired = res.data.data.isExpired;
            if (isExpired) {
                const routeList = this.$router.options.routes;
                let isHasSettingPermission = routeList.findIndex(item => item.path === '/setting');
                console.log('是否找到了该路由',isHasSettingPermission);
                if(isHasSettingPermission !== -1){
                    //跳转路由,打开重置密码框
                    this.$router.push({path:"/setting"});
                } else {
                    //无质检员设置权限
                    this.$alert('质检员身份过期，当前用户无质检员设置权限，请联系质检员进行密码重置！（质检员密码重置后刷新页面即可关闭此提示）', '提示', {
                        showConfirmButton:true,
                        showClose:false,
                        confirmButtonText: '刷新页面',
                        beforeClose: (action,instance,done) => {
                            //页面刷新
                            location.reload();
                        }
                    });
                }
            }
        },
        // 清除表单数据
        clearFormData() {
            this.dialogForm = {
                erpOrderNumber: '',
                stockOrderOrTask: '',
                totalQuantity: 0,
                productModel: '',
                mainCode: '',
                id:""
            };
        },
        //新增数据
        addBtn(){
            this.dialogFormVisible = true;
            this.dialogFormState = 0;
        },
        // 处理dialogFormHandle
        async dialogFormHandle(formName) {
            this.submitLoading = true
            const _this = this
            this.$refs[formName].validate(async (valid) => {
                // 校验通过，保存数据
                if (valid) {
                   if(_this.dialogFormState === 0){
                     //新增
                     await saveProductDetail({ ...this.dialogForm }).then(res => {
                        if (res.data.code === 200) {
                            this.$message.success("新增成功!")
                        }
                     }).finally(() => {
                            _this.clearFormData();
                            _this.dialogFormVisible = false;
                            this.getProductInfoList()
                     });
                   } else if (_this.dialogFormState === 1){
                        //编辑
                        reqUpdateProductionOrderDetails(_this.dialogForm).then(res => {
                            console.log('编辑排产表api',res);
                            if(res.data.code === 200){
                                this.$message({type:"success",message:"编辑成功!"});
                                _this.clearFormData();
                                _this.dialogFormVisible = false;
                                _this.getProductInfoList();
                            }
                        }).catch(err => {
                            this.$message({type:"error",message:err});
                        })
                   }
                }
                setTimeout(() => { this.submitLoading = false; }, 1000)
            });
        },
        // 删除数据
        async deleteRow(row) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () => {
                const res = await deleteProductOrderList(row.id);
                if (res.data.code === 200) {
                    this.$message.success("删除成功!")
                } else {
                    this.$message.error("删除失败!")
                }
                this.getProductInfoList()
            }).catch(() => {
                this.$message.warning("已取消删除!")
            })
        },
        //表格编辑按钮
        editRow (row){
            this.dialogFormVisible = true;
            this.dialogFormState = 1;
            //赋值
            this.dialogForm.erpOrderNumber = row.erpOrderNumber;
            this.dialogForm.stockOrderOrTask = row.stockOrderOrTask;
            this.dialogForm.totalQuantity = row.totalQuantity;
            this.dialogForm.productModel = row.productModel;
            this.dialogForm.mainCode = row.mainCode;
            this.dialogForm.id = row.id;
        },
        //模板下载按钮
        templateDownload_btn(){
            this.$confirm("即将下载排产表模板", '提示', { confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'})
                .then(async () => {
                    this.templateDownloadBtnLoading = true;  //导出按钮loading
                    let res = await reqExportTemplateOfProductionOrder();
                    if (res.status === 200) {
                        let blob = res.data;
                        let url = window.URL.createObjectURL(blob, { type: 'application/zip' });
                        const aLink = document.createElement('a');
                        aLink.href = url;
                        let timestamp = new Date().getTime();
                        aLink.setAttribute('download', '排产表模板_' + timestamp);
                        document.body.appendChild(aLink);
                        aLink.click();
                        document.body.removeChild(aLink);
                        this.$message.success('模板下载成功!');
                        this.templateDownloadBtnLoading = false;
                    } else {
                        this.$message.error('模板下载失败,请重试!');
                        this.templateDownloadBtnLoading = false;
                    }
                }).catch(() => {
                    this.$message({type:"info",message:"取消模板下载!"});
                });
        }
    }
}
</script>

<style lang='scss' scoped>
.content {
    width: 100%;
    height: calc(100vh - 50px);
    padding: 5vh 5vw;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .head {
        width: 100%;
        height: 20%;
        display: flex;
        flex-direction: column;
        .head-input {
            width: 100%;
            display: flex;
            justify-content: space-between;
            .input-item {
                width: 25%;
                display: flex;
                align-items: center;
                .item-label {
                    width: 5vw;
                    text-align: right;
                    margin-right: 5px;
                    font-size: 1vw;
                }
                .input {
                    width: 16vw;
                }
            }
        }
        .head-btn {
            margin: 2vw 0;
        }
    }
    .main {
        width: 100%;
        height: 75%;
        display: flex;
        flex-direction: column;
        .main-table {
            width: 100%;
            // height: 70vh;
            overflow: auto;
        }
        .main-pagination {
            margin: 0.5vw 0;
            display: flex;
            justify-content: flex-end;
            .pagination-content {
                display: flex;
                align-items: center;
                .content-tip {
                    margin: 0 1vw;
                    .tip {
                        margin: 0 0.2vw;
                    }
                    .tip-cur {
                        color: #0000ff;
                    }
                }
            }
        }
    }
}
::v-deep .el-table thead th {
    background: #efefef;
}
</style>